package com.typy.www.tpay.ui.acitivity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.typy.www.tpay.R;
import com.typy.www.tpay.ui.view.JuheGridView;
import com.typy.www.tpay.util.GlideUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.UiHelper;
import com.typy.www.tpay.util.picselect.AlbumAdapter;
import com.typy.www.tpay.util.picselect.AlbumModel;
import com.typy.www.tpay.util.picselect.PhotoModel;
import com.typy.www.tpay.util.picselect.PhotoSelectorDomain;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ImageAddActivity extends Activity implements OnItemClickListener {
	
	public static String IMAGE_MAX_COUNT = "ImageMaxCount";
	public static String IMAGE_FILE_LIST = "ImageFileList";
	public static String EXTRA_CODE = "ExtraCode";
	public static String RESULT_SELECTED_IMAGES = "SelectedImages";
	private ArrayList<File> imageFiles;
	private JuheGridView gvPhoto;
	private Button btnSelectOk;
	public static String RECCENT_PHOTO = null;
	
	private int imageWidth;
	private int maxCount;
	private int extraCode;
	private boolean IsQr;

	private TextView tvAlbum;
	private PhotoSelectorDomain photoSelectorDomain;
	private AlbumAdapter albumAdapter;
	private ListView lvAblum;
	private ArrayList<PhotoModel> selected;
	private PhotoAdapter adapter;
	int lvindex=0;
	
	/**
	 * 添加图片
	 */
	public static void addPhoto(Activity act, int requestCode, int maxCount, ArrayList<File> selectedPhotoList) {
		Intent intent = new Intent(act, ImageAddActivity.class);
		intent.putExtra(ImageAddActivity.IMAGE_MAX_COUNT, maxCount);
		intent.putExtra(ImageAddActivity.IMAGE_FILE_LIST, (ArrayList<File>) selectedPhotoList);
	    act.startActivityForResult(intent, requestCode);
	}
//	/**
//	 * 添加二维码
//	 */
//	public static void addQR(Activity act, int requestCode, int maxCount, ArrayList<File> selectedPhotoList) {
//		Intent intent = new Intent(act, ImageAddActivity.class);
//		intent.putExtra(ImageAddActivity.IMAGE_MAX_COUNT, maxCount);
//		intent.putExtra(ImageAddActivity.IMAGE_FILE_LIST, (ArrayList<File>) selectedPhotoList);
//		intent.putExtra("addQR", true);
//		act.startActivityForResult(intent, requestCode);
//	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_add);
		photoSelectorDomain = new PhotoSelectorDomain(getApplicationContext());
//
		photoSelectorDomain.getReccent(reccentListener);
		photoSelectorDomain.updateAlbum(albumListener);
//
		albumAdapter = new AlbumAdapter(getApplicationContext(),
				new ArrayList<AlbumModel>());
		selected = new ArrayList<>();
		lvAblum = (ListView) findViewById(R.id.lv_ablum_ar);
		tvAlbum = (TextView) findViewById(R.id.tv_album_ar);
		lvAblum.setAdapter(albumAdapter);
		lvAblum.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
				// TODO Auto-generated method stub
				AlbumModel current = (AlbumModel) parent.getItemAtPosition(position);
				for (int i = 0; i < parent.getCount(); i++) {
					AlbumModel album = (AlbumModel) parent.getItemAtPosition(i);
					if (i == position)
						album.setCheck(true);
					else
						album.setCheck(false);
				}
				lvAblum.setVisibility(View.GONE);
				gvPhoto.setVisibility(View.VISIBLE);
				adapter.notifyDataSetChanged();
				tvAlbum.setText(current.getName());
				// tvTitle.setText(current.getName());
				lvindex=position;
				if (current.getName().equals(RECCENT_PHOTO))
					photoSelectorDomain.getReccent(reccentListener);
				else
					photoSelectorDomain.getAlbum(current.getName(), reccentListener); // 鑾峰彇閫変腑鐩稿唽鐨勭収鐗�
			}
		});
		lvAblum.setVisibility(View.VISIBLE);
		DisplayMetrics dm = getResources().getDisplayMetrics();
		imageWidth = (dm.widthPixels - 20) / 3;

		gvPhoto = (JuheGridView) findViewById(R.id.gv_photo);
		gvPhoto.setHorizontalSpacing(10);
		gvPhoto.setVerticalSpacing(10);
		adapter = new PhotoAdapter(this);
		gvPhoto.setAdapter(adapter);
		gvPhoto.setOnItemClickListener(this);
		btnSelectOk = (Button) findViewById(R.id.btn_select_ok);
		gvPhoto.setVisibility(View.GONE);
		btnSelectOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent data=new Intent();
				data.putExtra(EXTRA_CODE, extraCode);
				data.putExtra(RESULT_SELECTED_IMAGES, imageFiles);
				setResult(Activity.RESULT_OK, data);
				finish();
			}

		});

		ImageButton btnBack = (ImageButton) findViewById(R.id.btn_select_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(lvAblum.getVisibility()== View.GONE){
					gvPhoto.setVisibility(View.GONE);
					lvAblum.setVisibility(View.VISIBLE);
				}else{
				setResult(Activity.RESULT_CANCELED, null);
				finish();
				}
			}

		});

		Intent intent = getIntent();
		maxCount = intent.getIntExtra(IMAGE_MAX_COUNT, 0);
		extraCode = intent.getIntExtra(EXTRA_CODE, 0);
		IsQr = intent.getBooleanExtra("addQR", false);
		Object obj = intent.getExtras().get(IMAGE_FILE_LIST);
		if (obj != null) {
			try {
				ArrayList<File> files = (ArrayList<File>) obj;
				imageFiles = (ArrayList<File>) files.clone();
			} catch (Exception e) {
				imageFiles = new ArrayList<File>();
			}
		} else
			imageFiles = new ArrayList<File>();
		updateBtnOk();
	}
	
	private void updateBtnOk() {
		if (maxCount > 0)
			btnSelectOk.setText(getString(R.string.action_ok) + String.format(" (%d/%d)", imageFiles.size(), maxCount));
		else
			btnSelectOk.setText(getString(R.string.action_ok) + String.format(" (%d)", imageFiles.size()));
	}

	/**
	 * 浏览相册、选择照片的Adapter
	 * @author zhimingyang
	 *
	 */
	private class PhotoAdapter extends BaseAdapter {
		private class Holder {
			private FrameLayout flRoot;
			private ImageView ivPhoto;
			private RelativeLayout rlCheck;
			private File file;
			private LinearLayout ll_index;
			private TextView tv_index;
		}
		
		private Cursor cursor;
		private Context context;
		
		public PhotoAdapter(Context context) {
			this.context = context;
			this.context = context;
			String[] projection = new String[] {
					MediaStore.Images.ImageColumns._ID,
					"_data",
					MediaStore.Images.ImageColumns.DATE_TAKEN };
			ContentResolver cr = getContentResolver();
			if (IsQr) {
				cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						projection, "_size > ?", new String[] {"1024"}, //过滤小于10k的文件
						MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
			} else {
				cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						projection, "_size > ?", new String[] {"1024"}, //过滤小于10k的文件
						MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
			}
		}
	
		@Override
		public int getCount() {
//			return cursor == null ? 0 : cursor.getCount();
			return selected==null?0:selected.size();
		}
		@Override
		public Object getItem(int position) {
			return null;
		}
	
		@Override
		public long getItemId(int position) {
			return 0;
		}
	
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				convertView = ImageAddActivity.this.getLayoutInflater().inflate(R.layout.item_seletc_photo, null);
				holder = new Holder();
				holder.flRoot = (FrameLayout) convertView.findViewById(R.id.fl_root);
				holder.ivPhoto = (ImageView) convertView.findViewById(R.id.iv_photo);
				holder.ivPhoto.setScaleType(ScaleType.FIT_CENTER);
				holder.rlCheck = (RelativeLayout) convertView.findViewById(R.id.rl_check);
				holder.ll_index=(LinearLayout) convertView.findViewById(R.id.ll_index);
				holder.tv_index=(TextView) convertView.findViewById(R.id.tv_index);
				convertView.setTag(holder);
			} else 
				holder = (Holder) convertView.getTag();
			holder.flRoot.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
//			cursor.moveToPosition(position);
			String uri = selected.get(position).getOriginalPath();
			File file = new File(uri);
			holder.file = file;
//			GlideUtils.getInstance().setImage(holder.file,holder.ivPhoto);
			ImageLoader.getInstance().displayImage("file://"+file.getPath(),holder.ivPhoto);
//			Glide.with(context).load(holder.file).
//			override(imageWidth, imageWidth).
//			placeholder(R.drawable.imgloading).
//			error(R.drawable.loaderr1).
//			crossFade().into(holder.ivPhoto);
			if (imageFiles.contains(holder.file)) {
				holder.rlCheck.setVisibility(View.VISIBLE);
			} else {
				holder.rlCheck.setVisibility(View.GONE);
			}
			for(int i=0;i<imageFiles.size();i++){
				if(holder.file.equals(imageFiles.get(i))){
					holder.tv_index.setText(i+1+"");
				}
			}
			return convertView;
		}

	}
	
	
	
	public interface OnLocalReccentListener {
		public void onPhotoLoaded(List<PhotoModel> photos);
	}

	public interface OnLocalAlbumListener {
		public void onAlbumLoaded(List<AlbumModel> albums);
	}

	private OnLocalAlbumListener albumListener = new OnLocalAlbumListener() {
		@Override
		public void onAlbumLoaded(List<AlbumModel> albums) {
			if(albums!=null&&albums.size()>1){
				albums.remove(0);
			}
			albumAdapter.update(albums);
		}
	};

	private OnLocalReccentListener reccentListener = new OnLocalReccentListener() {
		@Override
		public void onPhotoLoaded(List<PhotoModel> photos) {
//			for (PhotoModel model : photos) {
//				if (selected.contains(model)) {
//					model.setChecked(true);
//				}
//			}
			if(photos!=null){
				selected.clear();
				selected.addAll(photos);
				adapter.notifyDataSetChanged();
				gvPhoto.smoothScrollToPosition(0);
			}

//			 reset(); //--keep selected photos

		}
	};
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {

		Object tag = view.getTag();

		if (tag instanceof PhotoAdapter.Holder) {
			PhotoAdapter.Holder holder = (PhotoAdapter.Holder) tag;

			if (holder.rlCheck.getVisibility() == View.VISIBLE) {
				holder.rlCheck.setVisibility(View.GONE);
				imageFiles.remove(holder.file);
				adapter.notifyDataSetChanged();
			}
			else  {
				if (maxCount > 0 && imageFiles.size() >= maxCount) {
					UiHelper.showToast(this, "最多选择" + String.valueOf(maxCount) + "张图片!");
				} else {
					holder.rlCheck.setVisibility(View.VISIBLE);
					imageFiles.add(holder.file);
					for(int i=0;i<imageFiles.size();i++){
						if(holder.file.equals(imageFiles.get(i))){
							holder.tv_index.setText(i+1+"");
						}
					}
				}
			}
			updateBtnOk();
		}
	}


	@Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
	            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	                     //TODO something
	            	if(lvAblum.getVisibility()== View.GONE){
						gvPhoto.setVisibility(View.GONE);
						lvAblum.setVisibility(View.VISIBLE);
					}else{
					setResult(Activity.RESULT_CANCELED, null);
					finish();
					}
	                    return true;
	              }
	            
	              return super.onKeyDown(keyCode, event);
	 }
}
